using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace ParangonBiz.Data
{
	[DataObject]
	[Serializable]
	public partial class EmailTemplate
	{
		#region Constants

		private const string TableName = "[dbo].[EmailTemplate]";

		#endregion

		#region Properties

		public int? TemplateId { get; set; }
		public string Subject { get; set; }
		public string Content { get; set; }
		public int? TemplateType { get; set; }
		public DateTime? CreateDate { get; set; }
		public DateTime? LastModifiedDate { get; set; }

		#endregion

		#region Methods

		#region Mapping Methods

		protected void MapTo(DataSet ds)
		{
			if (ds == null)
				ds = new DataSet();

			if (ds.Tables[TableName] == null)
				ds.Tables.Add(TableName);

			ds.Tables[TableName].Columns.Add("TemplateId", typeof(Int32));
			ds.Tables[TableName].Columns.Add("Subject", typeof(String));
			ds.Tables[TableName].Columns.Add("Content", typeof(String));
			ds.Tables[TableName].Columns.Add("TemplateType", typeof(Int32));
			ds.Tables[TableName].Columns.Add("CreateDate", typeof(DateTime));
			ds.Tables[TableName].Columns.Add("LastModifiedDate", typeof(DateTime));

			DataRow dr = ds.Tables[TableName].NewRow();

			dr["TemplateId"] = TemplateId ?? (object)DBNull.Value;
			dr["Subject"] = Subject ?? (object)DBNull.Value;
			dr["Content"] = Content ?? (object)DBNull.Value;
			dr["TemplateType"] = TemplateType ?? (object)DBNull.Value;
			dr["CreateDate"] = CreateDate ?? (object)DBNull.Value;
			dr["LastModifiedDate"] = LastModifiedDate ?? (object)DBNull.Value;

			ds.Tables[TableName].Rows.Add(dr);
		}

		protected void MapFrom(DataRow dr)
		{
			TemplateId = dr["TemplateId"] != DBNull.Value ? Convert.ToInt32(dr["TemplateId"]) : TemplateId = null;
			Subject = dr["Subject"] != DBNull.Value ? Convert.ToString(dr["Subject"]) : Subject = null;
			Content = dr["Content"] != DBNull.Value ? Convert.ToString(dr["Content"]) : Content = null;
			TemplateType = dr["TemplateType"] != DBNull.Value ? Convert.ToInt32(dr["TemplateType"]) : TemplateType = null;
			CreateDate = dr["CreateDate"] != DBNull.Value ? Convert.ToDateTime(dr["CreateDate"]) : CreateDate = null;
			LastModifiedDate = dr["LastModifiedDate"] != DBNull.Value ? Convert.ToDateTime(dr["LastModifiedDate"]) : LastModifiedDate = null;
		}

		public static List<EmailTemplate> MapFrom(DataSet ds)
		{
			// Initialise Collection.
			List<EmailTemplate> objects = new List<EmailTemplate>();

			// Validation.
			if (ds == null)
				throw new ApplicationException("Cannot map to dataset null.");

			if (ds.Tables[TableName].Rows.Count == 0)
				return objects;

			if (ds.Tables[TableName] == null)
				throw new ApplicationException("Cannot find table [dbo].[EmailTemplate] in DataSet.");

			if (ds.Tables[TableName].Rows.Count < 1)
				throw new ApplicationException("Table [dbo].[EmailTemplate] is empty.");

			// Map DataSet to Instance.
			foreach (DataRow dr in ds.Tables[TableName].Rows)
			{
				EmailTemplate instance = new EmailTemplate();
				instance.MapFrom(dr);
				objects.Add(instance);
			}

			// Return collection.
			objects.Sort();
			return objects;
		}

		#endregion

		#region CRUD Methods

		public static EmailTemplate Get(Int32 templateId)
		{
			EmailTemplate instance = new EmailTemplate();

			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspEmailTemplate_SELECT";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, templateId))
			{
				using (DataSet ds = db.ExecuteDataSet(dbCommand))
				{
					if (ds == null || ds.Tables[0].Rows.Count == 0) throw new ApplicationException(String.Format("Could not get EmailTemplate ID:{0} from Database.", templateId));
					ds.Tables[0].TableName = TableName;

					instance.MapFrom(ds.Tables[0].Rows[0]);
				}
			}
			return instance;
		}

		#region INSERT

		private void Insert(String subject, String content, Int32? templateType, DateTime? createDate, DateTime? lastModifiedDate, DbTransaction transaction = null)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspEmailTemplate_INSERT";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, subject, content, templateType, createDate, lastModifiedDate))
			{
				TemplateId = Convert.ToInt32(transaction == null ? db.ExecuteScalar(dbCommand) : db.ExecuteScalar(dbCommand, transaction));
			}
		}

		/// <summary>
		/// Insert current EmailTemplate to database.
		/// </summary>
		/// <param name="transaction">optional SQL Transaction</param>
		private void Insert(DbTransaction transaction = null)
		{
			Insert(Subject, Content, TemplateType, CreateDate, LastModifiedDate, transaction);
		}

		#endregion

		#region UPDATE

		private static void Update(Int32? templateId, String subject, String content, Int32? templateType, DateTime? createDate, DateTime? lastModifiedDate, DbTransaction transaction)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspEmailTemplate_UPDATE";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand))
			{
				db.DiscoverParameters(dbCommand);

				dbCommand.Parameters["@templateId"].Value = templateId;
				dbCommand.Parameters["@subject"].Value = subject;
				dbCommand.Parameters["@content"].Value = content;
				dbCommand.Parameters["@templateType"].Value = templateType;
				dbCommand.Parameters["@createDate"].Value = createDate;
				dbCommand.Parameters["@lastModifiedDate"].Value = lastModifiedDate;

				if (transaction == null)
					db.ExecuteNonQuery(dbCommand);
				else
					db.ExecuteNonQuery(dbCommand, transaction);
			}
		}

		private static void Update(Int32? templateId, String subject, String content, Int32? templateType, DateTime? createDate, DateTime? lastModifiedDate)
		{
			Update(templateId, subject, content, templateType, createDate, lastModifiedDate, null);
		}

		private static void Update(EmailTemplate emailTemplate)
		{
			emailTemplate.Update();
		}

		private static void Update(EmailTemplate emailTemplate, DbTransaction transaction)
		{
			emailTemplate.Update(transaction);
		}

		/// <summary>
		/// Updates changes to the database.
		/// </summary>
		/// <param name="transaction">optional SQL Transaction</param>
		private void Update(DbTransaction transaction)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspEmailTemplate_UPDATE";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand))
			{
				db.DiscoverParameters(dbCommand);

				dbCommand.Parameters["@templateId"].SourceColumn = "TemplateId";
				dbCommand.Parameters["@subject"].SourceColumn = "Subject";
				dbCommand.Parameters["@content"].SourceColumn = "Content";
				dbCommand.Parameters["@templateType"].SourceColumn = "TemplateType";
				dbCommand.Parameters["@createDate"].SourceColumn = "CreateDate";
				dbCommand.Parameters["@lastModifiedDate"].SourceColumn = "LastModifiedDate";

				using (DataSet ds = new DataSet())
				{
					MapTo(ds);
					ds.AcceptChanges();
					ds.Tables[0].Rows[0].SetModified();

					if (transaction == null)
						db.UpdateDataSet(ds, TableName, null, dbCommand, null, UpdateBehavior.Standard);
					else
						db.UpdateDataSet(ds, TableName, null, dbCommand, null, transaction);
				}
			}
		}

		/// <summary>
		/// Updates changes to the database.
		/// </summary>
		private void Update()
		{
			Update((DbTransaction)null);
		}
		#endregion

		#region DELETE
		public static void Delete(Int32? templateId, DbTransaction transaction)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspEmailTemplate_DELETE";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, templateId))
			{
				if (transaction != null)
				{
					db.ExecuteNonQuery(dbCommand, transaction);
				}
				else
				{
					db.ExecuteNonQuery(dbCommand);
				}
			}
		}

		public static void Delete(Int32? templateId)
		{
			Delete(templateId, null);
		}

		/// <summary>
		/// Delete current EmailTemplate from database.
		/// </summary>
		/// <param name="transaction">optional SQL Transaction</param>
		public void Delete(DbTransaction transaction)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspEmailTemplate_DELETE";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, TemplateId))
			{
				if (transaction != null)
				{
					db.ExecuteNonQuery(dbCommand, transaction);
				}
				else
				{
					db.ExecuteNonQuery(dbCommand);
				}
			}
			TemplateId = null;
		}

		/// <summary>
		/// Delete current EmailTemplate from database.
		/// </summary>
		public void Delete()
		{
			Delete((DbTransaction)null);
		}

		#endregion

		#region SEARCH

		private static List<EmailTemplate> Search(Int32? templateId = null, String subject = null, String content = null, Int32? templateType = null, DateTime? createDate = null, DateTime? lastModifiedDate = null)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspEmailTemplate_SEARCH";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, templateId, subject, content, templateType, createDate, lastModifiedDate))
			{
				using (DataSet ds = db.ExecuteDataSet(dbCommand))
				{
					ds.Tables[0].TableName = TableName;
					return MapFrom(ds);
				}
			}
		}

		private static List<EmailTemplate> Search(EmailTemplate searchObject)
		{
			return Search(searchObject.TemplateId, searchObject.Subject, searchObject.Content, searchObject.TemplateType, searchObject.CreateDate, searchObject.LastModifiedDate);
		}

		#endregion

		#endregion

		#endregion
	}
}